package com.rice.study.Service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rice.study.Service.TestService;
import com.rice.study.dao.Tester;
import com.rice.study.mapper.TestMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service("TestService")
@Slf4j
public class TestServiceImpl implements TestService {

//    Logger log = LoggerFactory.getLogger(TestServiceImpl.class);
    @Autowired
    TestMapper testMapper;

//    @Autowired
//    private JedisPool jedisPool;

    @Autowired
    private RedissonClient redisson;



    ExecutorService threadPool = Executors.newFixedThreadPool(5);


    @Override
    public Tester getTestDb(Integer id) {
        String key = UUID.randomUUID().toString().replaceAll("-","");
            log.info("test key is - {}", key);
//        jedisPool.getResource().set(key, "test");
//        log.info(jedisPool.getResource().setnx(key, key)+"");
//        jedisPool.getResource().expire(key, 100000);
//        log.info(jedisPool.getResource().get(key));


        for (int i = 0; i < 1000; i++) {
//            new Thread(testLock()).start();
            threadPool.execute(()-> testLock());
        }

        log.info("end redisson");

        return testMapper.getById(id);
    }

    private void testLock() {


        try {
            Integer t =  (int)Math.random()* 100;
            Thread.currentThread().sleep(t);
            Thread.currentThread().setName(UUID.randomUUID().toString());
            RLock lock1 = redisson.getLock("test-redisson");
            lock1.lock(10,TimeUnit.HOURS);
            Boolean try1 = lock1.tryLock(10,TimeUnit.HOURS);
            lock1.unlock();
            log.info(Thread.currentThread().getName() +" 获取锁的结果 ："+ try1);
//            log.info("end redisson");
        }catch (Throwable t){
            log.info("error redisson");
        }

    }

    @Override
    @Cacheable(value="users", key ="#id")
    public Tester getById(Integer id) {
        Tester tester = testMapper.getById(id);
        log.info("tester id is - "+ id +" ,info -"+ (tester == null? " null ": JSONObject.toJSONString(tester)));
        return tester;
    }

    @Override
    @CachePut(value= "users", key = "#t.id")
    public Integer save(Tester t) {
//        return testMapper.batchSave(Arrays.asList(t));
        testMapper.save(t);
        return t.getId() ;
    }
}
